package pkg

import (
	"errors"
	"github.com/sony/sonyflake"
	"math/rand"
	"sync"
	"time"
)

// https://juejin.cn/post/6844904035380658190
// https://www.fahsa.cn/post/go/snowflake-sonyflake/

func SnowflakeInit() (*sonyflake.Sonyflake, error) {
	var settings sonyflake.Settings

	//if SnowflakeConfig.StartTime != "" {
	//	t, err := time.Parse("2006-01-02", SnowflakeConfig.StartTime)
	//	if err != nil {
	//		return errors.New(err.Error())
	//	}
	//	settings.StartTime = t
	//}
	//
	//if SnowflakeConfig.MachineID != 0 {
	//	settings.MachineID = func() (uint16, error) {
	//		return SnowflakeConfig.MachineID, nil
	//	}
	//}

	sf := sonyflake.NewSonyflake(settings)
	if sf == nil {
		return nil, errors.New("sonyflake not created")
	}
	return sf, nil
}

// https://blog.csdn.net/qq_32212587/article/details/124424106
// 生成随机id， 在 sonyflake 生成失败的代替
var rg = struct {
	sync.Mutex
	rand *rand.Rand
}{
	rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}

// https://www.cnblogs.com/niuben/p/13925133.html
// Int63nRange 返回一个取值范围在[0,n)的伪随机int32值，如果n<=0会panic。
func int63nRange(min, max int64) int64 {
	rg.Lock()
	defer rg.Unlock()
	return rg.rand.Int63n(max-min) + min
}

// GetId 注：** 如果作为 Mysql 主键使用，字段类型需使用 bigint 类型。`user_id` bigint(20) NOT NULL, UNIQUE KEY `idx_user_id` (`user_id`) USING BTREE
func GetId(sf *sonyflake.Sonyflake) uint64 {
	id, err := sf.NextID()
	if err != nil {
		id = uint64(int63nRange(1926425572, 1926425572223607))
	}
	// return fmt.Sprintf("%d", id)
	return id
}
